<template>
  <div class="setting-content inside-comment">
    <h2 class="setting-header">
      <strong>常见问题</strong>
      <el-button type="primary" @click="addQuestion">添加类目/问答</el-button>
    </h2>
    <div class="question-container">
      <div class="left-question">
        <div 
          v-for="(category, key) in questionList" 
          :key="key"
          class="category-item"
          :class="{ active: activeCategory === key }"
          @click="changeCategory(key)"
        >
          <div class="left-tit">{{ getCategoryQuestion(key).question }} </div>
          <div class="right-option">
            <el-icon v-if="getCategoryQuestion(key).display" class="turn-off show-icon" @click="changeDisplay(key,!getCategoryQuestion(key).display)"><View /></el-icon>
            <el-icon v-else  class="turn-open " @click="changeDisplay(key,!getCategoryQuestion(key).display)"><Hide /></el-icon>
            <el-icon @click="delQA(key,'分类')" class="del-icon"><Delete /></el-icon>
          </div>
        </div>
      </div>
      
      <div class="right-answer">
        <div v-if="activeCategory" class="answer-list">
          <div 
            v-for="item in getCurrentAnswers()" 
            :key="item.id"
            class="answer-item"
          >
            <div class="top-info">
              <h3 class="item-question">{{ item.question }}</h3>
              <div class="right-option">
                <el-icon v-if="item.display" class="turn-off show-icon" @click="changeDisplay(item.id,!item.display)"><View /></el-icon>
                <el-icon v-else  class="turn-open " @click="changeDisplay(item.id,!item.display)"><Hide /></el-icon>
                <el-icon class="del-icon" @click="delQA(item.id,'问答')"><Delete /></el-icon>
              </div>
            </div>
            <p v-if="item.answer">{{ item.answer }}</p>
            <p v-else class="no-answer">暂无答案</p>
          </div>
        </div>
        <div v-else class="no-category-selected">
          请从左侧选择一个分类
        </div>
      </div>
    </div>
    
    <el-dialog v-model="questionVisible" :title="questionTitle" width="600px" class="question-dialog">
      <el-form :model="questionForm" :rules="rules" label-width="80px">
        <el-form-item label="是否类目" prop="category">
          <el-switch v-model="questionForm.category"></el-switch>
        </el-form-item>
        <el-form-item label="关联类目" prop="affiliating" v-if="!questionForm.category">
          <el-select v-model="questionForm.affiliating" placeholder="选择类目" style="width: 240px">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="questionForm.category ? '类名名称' : '问题'" prop="question">
          <el-input placeholder="输入类名名称" v-model="questionForm.question"></el-input>
        </el-form-item>
        <el-form-item label="答案" prop="answer" v-if="!questionForm.category">
          <el-input placeholder="输入答案" v-model="questionForm.answer"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="questionVisible = false">取消</el-button>
          <el-button type="primary" @click="saveQuestion">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import  { ref, reactive, onMounted, computed } from 'vue'
import { 
  getQA,
  saveQA,
  deleteQAQA,
  changeDisplayQa
 } from '@/api/question'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Hide, View } from '@element-plus/icons-vue'

const questionList = ref([])
const getQuestion = async () => {
  const res = await getQA();
  if(res.code === 20000){
    questionList.value = res.data
  }
}
const activeCategory = ref(null);

const categoryOptions = computed(() => {
  const options = [];
  for (const key in questionList.value) {
    const items = questionList.value[key];
    for (const item of items) {
      if (item.category) {
        options.push({
          label: item.question,
          value: item.id
        });
      }
    }
  }
  return options;
});
// 获取分类标题（找到category为true的项）
const getCategoryQuestion = (key) => {
  const category = questionList.value[key].find(item => item.category);
  return category ? category : '未命名分类';
};

// 获取当前分类下的答案（排除category为true的项）
const getCurrentAnswers = () => {
  if (!activeCategory.value) return [];
  return questionList.value[activeCategory.value].filter(item => !item.category);
};

// 切换分类
const changeCategory = (key) => {
  activeCategory.value = key;
};

const defaultForm = reactive({
  id: "",
  category: true,
  affiliating: "",
  question: "",
  answer: ""
})
const questionForm = ref({...defaultForm})
const questionVisible = ref(false)
const questionTitle = ref('')

const addQuestion = async () => {
  questionForm.value = {...defaultForm}
  questionVisible.value = true;
}
//保存 修改 类目/问答
const saveQuestion = async () => {
  questionTitle.value = '新增类目/问答'
  const res = await saveQA(questionForm.value)
  if(res.code === 20000){
    ElMessage.success("保存成功")
    getQuestion()
    questionVisible.value = false;
  }
}

//删除类目
const delQA = async (id,title) => { 
  console.log("id",id);
  ElMessageBox.confirm(`是否删除该${title}？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await deleteQAQA({ id: id });
    if(res.code === 20000){
      ElMessage.success("删除成功");
      getQuestion();
    }
  })
}
//修改显示状态
const changeDisplay = async (id, display) => { 
  const res = await changeDisplayQa({ id: id, display: display });
  if(res.code === 20000){
    ElMessage.success("修改成功");
    getQuestion();

  }
}
onMounted(() => {
  getQuestion().then(() => {
    // 获取第一个分类的key
    const keys = Object.keys(questionList.value);
    if (keys.length > 0) {
      activeCategory.value = keys[0];
    }
  });
});
</script>

<style scoped lang="scss">
.setting-header{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.question-container{
  display: flex;
  
  .left-question {
    width: 300px;
    border-right: 1px solid #eee;
    overflow-y: auto;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0,0,0,0.05);
    border: 1px solid $borderColor;
    border-radius: 5px;
   
  }

  .right-answer {
    flex: 1;
    padding: 20px;
    margin-left: 10px;
    overflow-y: auto;
    border: 1px solid $borderColor;

  }

  .category-item {
    padding: 12px 16px;
    margin-bottom: 8px;
    cursor: pointer;
    border-radius: 4px;
    transition: all 0.3s;
    position: relative;
    display: flex;
    .left-tit{
      flex: 1;
    }
    .right-option{
      display: flex;
      align-items: center;
      i{
        margin: 0 5px;
        font-size: 18px;
        color: #666;
      }
      .show-icon{
        color: $mainColor;
      }
      .del-icon{
        color: #f56c6c;
      }
    }
   
  }

  .category-item:hover {
    background-color: #f5f5f5;
  }

  .category-item.active {
    background-color: #f5f5f5;
  }

  .answer-item {
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px dashed #eee;
    position: relative;
    .top-info{
      display: flex;
      margin-bottom: 12px;
      .item-question{
        flex: 1;
        color: $black_2;
      }
      .right-option{
        display: flex;
        align-items: center;
        i{
          margin: 0 5px;
          font-size: 18px;
          color: #666;
        }
        .show-icon{
          color: $mainColor;
        }
        .del-icon{
          color: #f56c6c;
        }
      }
    }
  
    p {
      color: #666;
      line-height: 1.6;
    }
    
  }

  .no-answer {
    color: #999;
    font-style: italic;
  }

  .no-category-selected {
    display: flex;
    height: 100%;
    align-items: center;
    justify-content: center;
    color: #999;
  }
}

</style>